package appfuse.framework.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.httpclient.NameValuePair;

/**
 * Encodes a string using MD5 hashing
 * 
 * @author Rafael Steil
 * @version $Id: MD5.java,v 1.1.2.1.2.5 2009/04/21 06:20:30 peiyf Exp $
 */
public class MD5 {
	/**
	 * Encodes a string
	 * 
	 * @param str
	 *            String to encode
	 * @return Encoded String
	 * @throws NoSuchAlgorithmException
	 */
	public static String crypt(String str) {
		// return str;
		if (str == null || str.length() == 0) {
			throw new IllegalArgumentException(
					"String to encript cannot be null or zero length");
		}

		StringBuffer hexString = new StringBuffer();

		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes("UTF-8"));
			byte[] hash = md.digest();

			for (int i = 0; i < hash.length; i++) {
				if ((0xff & hash[i]) < 0x10) {
					hexString.append("0"
							+ Integer.toHexString((0xFF & hash[i])));
				} else {
					hexString.append(Integer.toHexString(0xFF & hash[i]));
				}
			}
		} catch (NoSuchAlgorithmException e) {

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return hexString.toString();
	}

	public static String crypt2(String str) {
		// return str;
		if (str == null || str.length() == 0) {
			throw new IllegalArgumentException(
					"String to encript cannot be null or zero length");
		}

		StringBuffer hexString = new StringBuffer();

		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			byte[] hash = md.digest();
			for (byte b : md.digest(str.toString().getBytes("UTF-8"))) {
				hexString.append(Integer.toHexString((b & 0xf0) >>> 4));
				hexString.append(Integer.toHexString(b & 0x0f));
			}
		} catch (NoSuchAlgorithmException e) {

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return hexString.toString();
	}

	// 测试
	public static void main(String[] args) {
		System.out.println(crypt(5 + "97C47DV3-54F2-35Dd-FE8X-58X4DVA33FB"));
	}
}
